/**
 * 物料相关
 */
var jijiaMethod = '1';
var totalPrice = 0;
$(document).ready(function () {
	if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0"){
		var $moudle = $('#data-moudle');
		var module = $moudle.val();
		var $id = $('#data-id');
		var id = $id.val();
	}else {
		var $body = $('body');
		var module = $body.data('moudle');
		var id = $body.data('id');
	}

	//预算总价计算
	var $totalPrice = $('#totalPrice');
	var $requestItemTable = $('#datatable-requestItemTable');
	var pagePriceSum = 0;//当前页码原始值
	totalPrice = (+$totalPrice.html())||0;
	$requestItemTable.on('input propertychange','.js-change', function () {
		var sum = countTotalPrice();
		totalPrice = totalPrice + sum - pagePriceSum;
		pagePriceSum = sum;
		$totalPrice.html((totalPrice + sum - pagePriceSum).toFixed(2));
        var param = +this.value;
        if (!param || param <= 0) {
            RFQ.error('请输入大于0的数字');
        }
	});

	//预算价选择项点击
	$requestItemTable.on('click','.dropdown-menu a', function () {
		var index = $(this).parent().index();
		var url = ctx+'/rfqRequest/updateSalePriceByRecent';
		if(index == 1){
			url = ctx+'/rfqRequest/updateSalePriceByHistory';
		}
		//设置默认预算价
		$requestItemTable.find('input[data-name$="salePrice"]').each(function () {
			if(!this.value.length){
				this.value = 0;
			}
		});

		var rfqDtable = $requestItemTable.data('_rfqDTable');
		//保存当页数据
		if(rfqDtable.options.beforePagination.call(rfqDtable)){
			RFQ.post(url,{}, function (data) {
				totalPrice = +data.obj;
				$totalPrice.html(totalPrice.toFixed(2));
			},false);
			rfqDtable.load();
		}
	});

	//计算总价
	function countTotalPrice(){
		var sum = 0;
		$requestItemTable.find("input[data-name='requestAmount']").each(function(){
			var $this = $(this);
			var $tr = $this.closest('tr');
			var requestAmount = +this.value;
			var salePrice = +$tr.find('input[data-name="salePrice"]').val();
			!requestAmount && (requestAmount = 0);
			!salePrice && (salePrice = 0);
			sum += (requestAmount*salePrice);
		});
		return sum;
	}


	//物料分页加载
	//var $zuiDataTable = $('#requestItemTable');
	(function () {
		var clsMapping = {requestAmount:'js-change',salePrice:'js-change',requestDeliveryDate:'form-date'};
		var inputTpl = '<input type="text" class="form-control input-sm {cls}" data-name="{name}" value="{value}" data-ext="{ext}" maxlength="{limit}">';//输入框
		var _mappingNames = ['materialNo','materialName','requestAmount','unit','character','producer','specification','salePrice','requestDeliveryDate','memo'];
		var _mappingLimits ={materialNo:200,materialName:400,requestAmount:25,unit:20,character:200,producer:50,specification:30,salePrice:25,requestDeliveryDate:20,memo:2000};
		//获取自定义字段
		var extColsMapping = {};
		$('#requestItemTable').find('th.ext-col').each(function (i) {
			var $this = $(this);
			var extCode = $this.data('extcode');
			var valName = 'itemValue_'+(i+1);
			extColsMapping[valName] = extCode;
			_mappingNames.push(valName);
		});
		var options = {
			datatype: 'json',
			url:ctx+'/rfqRequest/rfqRequestItemList',
            sord: 'ASC',
            sidx: 'SEQ',
			mappingNames: _mappingNames,
			cellFormat: function (name,val,row,index) {
				var tmp = inputTpl.format({name:name,value:val||'',cls:clsMapping[name]||'',ext:extColsMapping[name]||'',limit:_mappingLimits[name]||100});
				//if(row && name == 'materialNo'){
				//	tmp += '<input type="hidden" data-name="id" value="'+(row.id||'')+'">';
				//}
				return tmp;
			},
			afterLoadData: function () {
				var that = this;
				this.visibleObj.find('.form-date').datetimepicker({
					weekStart: 1,
					todayBtn:  1,
					autoclose: 1,
					todayHighlight: 1,
					startView: 2,
					minView: 2,
					forceParse: 0,
					format: "yyyy-mm-dd"
				});

                //给要求交货期添加事件
                $('.requestDeliveryDate.datetimepicker .datetimepicker-days').on('click', 'tbody td,tfoot th', function () {
                    setTimeout(function () {
                        $requestItemTable.find('input[data-name="requestDeliveryDate"]').val($('#requestDeliveryDate2.form-control').eq(1).val());
                    }, 100);
                    var extras = that.fetchChanges('requestItemList');
                    RFQ.post(ctx + '/rfqRequest/check4Item', extras, function (msg) {
                        if (msg.rspcod == '200') {
                            return;
                        } else if (msg.rspcod == '201') {
                            RFQ.warn(msg.rspmsg)
                        }
                    }, false);
                });
				$('#datatable-requestItemTable').find('.datatable-head .fixed-left table th').css({'height':'69px','minHeight':'69px'})
				pagePriceSum = countTotalPrice();
			},
			beforePagination: function () {
				//分页前保存数据
				var that = this;
				var extras = that.fetchChanges('requestItemList');
				RFQ.d(extras);
				var canPass = false;
				RFQ.post(ctx+'/rfqRequest/save2temp',extras, function (msg) {
					//数据置空
					canPass = true;
					that.deleteIds = [];
				},false);
				return canPass;
			}
		};

		var rfqDTable = RFQ.dataTable('#requestItemTable').init(options);

		$requestItemTable.data('_rfqDTable',rfqDTable);

		if('edit'!=module){
			rfqDTable.load({},true);
		}else{
			var $biddingMethod = $("#biddingMethod");
			if($biddingMethod){
				var value = $("#biddingMethod").val();
				if(value =='0'){
					$("#itemTable").append('<th data-width="180" class="flex-col" name="RfqRequestItemBo.startPrice">起拍价</th>');
					$("#itemTable").append('<th data-width="180" class="flex-col" name="RfqRequestItemBo.priceGrad">梯度</th>');

					rfqDTableInit(true);
				}else{
					rfqDTableInit(false);
				}
			}


			rfqDTable.load();
			/*$('#totalPrice').html(pagePriceSum.toFixed(2));*/
		}

		//新增一行数据
		$('#addRow').on('click', function () {
			rfqDTable.addRow();
		});

		//清空物料
		$('#clearData').on('click', function () {
			RFQ.post(ctx+'/rfqRequest/deleteRequestItemTmpData',{}, function () {
				rfqDTable.clear();
				rfqDTable.deleteIds = [];
				totalPrice = 0;
				pagePriceSum = 0;
				$totalPrice.html(totalPrice.toFixed(2));
				rfqDTable.load();//清空数据后刷新jqgrid
			},false);
		});

		//删除一行
		$requestItemTable.on('click','.js-del', function () {
			var $this = $(this);
			var $tr = $this.closest('tr');
			var index = $tr.data('index');
			var sumTmp = pagePriceSum;
			//重新计算当前页的总价
			//rfqDTable.delRow(index);
			totalPrice = (+$totalPrice.html())||0;
			totalPrice -= (sumTmp - pagePriceSum);
			$totalPrice.html(totalPrice.toFixed(2));
			var id = $this.next('input').val();
			if(id){
				RFQ.post(ctx+'/rfqRequest/deleteRequestItemTmpData2?id='+id,null,function () {
					rfqDTable.deleteIds.push(id);
					rfqDTable.load();
				},false);
			}else{
				rfqDTable.delRow(index);
			}
		});
	})();

	/*按总价竞价，按物料竞价装换调整物料*/
	$('#checkedDiv3').on('change',':radio', function () {
		var biddingMethod = (this.value =='0');
		jijiaMethod = '0';
		//判断系统自动延时和竞价次数限制选中哪一个
		var isCheck = $('input[name="radioOptions3"]:checked').val();

		if(biddingMethod){
			//按物料竞价
			if(isCheck=='0'){
				$('#quotationUpperDate').attr("disabled",true);
				$('#maxExtendTime').attr("disabled",true);
			}else{
				$('#lastTime').attr("disabled",true);
				$('#totalNum').attr("disabled",true);
			}
			$('#currency').attr("disabled",true);
			$('input[name="requestBo.startPrice"]').attr("disabled",true);
			$('input[name="requestBo.priceGrad"]').attr("disabled",true);

			$('#quotationUpperDate2').removeAttr("disabled");
			$('#maxExtendTime2').removeAttr("disabled");
			$('#currency2').removeAttr("disabled");

			$("#itemTable").append('<th data-width="180" class="flex-col" name="RfqRequestItemBo.startPrice">起拍价</th>');
			$("#itemTable").append('<th data-width="180" class="flex-col" name="RfqRequestItemBo.priceGrad">梯度</th>');
			rfqDTableInit(biddingMethod);
		}else{
			jijiaMethod = '1';
			//按总价竞价
			if(isCheck=='0'){
				$('#quotationUpperDate').removeAttr("disabled");
				$('#maxExtendTime').removeAttr("disabled");
			}else{
				$('#lastTime').removeAttr("disabled");
				$('#totalNum').removeAttr("disabled");
			}
			$('#currency').removeAttr("disabled");
			$('#startPrice').removeAttr("disabled");
			$('#priceGrad').removeAttr("disabled");

			$('#quotationUpperDate2').attr("disabled",true);
			$('#maxExtendTime2').attr("disabled",true);
			$('#currency2').attr("disabled",true);

			$('input[name="requestBo.startPrice"]').removeAttr("disabled");
			$('input[name="requestBo.priceGrad"]').removeAttr("disabled");

			$('th[name="RfqRequestItemBo.startPrice"]').remove();
			$('th[name="RfqRequestItemBo.priceGrad"]').remove();
			rfqDTableInit(biddingMethod);
		}
	})

	function rfqDTableInit(biddingMethod) {
		var _mappingNames = ['materialNo', 'materialName', 'requestAmount', 'unit', 'character', 'producer','specification',  'salePrice', 'requestDeliveryDate', 'memo'];
		//获取自定义字段
		var extColsMapping = {};
		$('#requestItemTable').find('th.ext-col').each(function (i) {
			var $this = $(this);
			var extCode = $this.data('extcode');
			var valName = 'itemValue_' + (i + 1);
			extColsMapping[valName] = extCode;
			_mappingNames.push(valName);
		});
		if(biddingMethod){
			_mappingNames.push("startPrice");
			_mappingNames.push("priceGrad");
		}
		var $requestItemTable = $('#datatable-requestItemTable');
		$totalPrice.html(totalPrice.toFixed(2));
		var cals = scanElement();
		// RFQ.d(cals);
		var rfqDTable = $requestItemTable.data('_rfqDTable');
		rfqDTable.acceptChanges();
		var rows =  rfqDTable.rows;
		// RFQ.d(rows);
		$.each(rows, function (i,d) {
			if(biddingMethod){
				d.data[d.data.length] = rfqDTable.options.cellFormat('startPrice',undefined,d.data,d.data.length);
				d.data[d.data.length] = rfqDTable.options.cellFormat('priceGrad',undefined,d.data,d.data.length);
			}else if(d.data.length != cals.length){
				d.data = d.data.slice(0,(d.data.length-2));
			}

		});
        rfqDTable.cols = cals;
        rfqDTable.mappingNames = _mappingNames;


		rfqDTable._load(rows);
		$requestItemTable.data('_rfqDTable',rfqDTable);
	}
});




//扫描页面物料多少列
function scanElement(){
	var cols =[];
	var $th;

	$("#requestItemTable").find('thead > tr:first').children('th').each(function() {
		$th = $(this);
		cols.push($.extend({
			text: $th.html(),
			flex: false || $th.hasClass('flex-col'),
			width: 'auto',
			cssClass: $th.attr('class'),
			css: $th.attr('style'),
			type: 'string',
			ignore: $th.hasClass('ignore'),
			sort: !$th.hasClass('sort-disabled'),
			mergeRows: $th.attr('merge-rows')
		}, $th.data()));
	});
	return cols;
}


















//excel模板导出
function exportExcelModel(){
	location.href=ctx+'/rfqRequestItem/exportTemplate2?biddingMethod='+jijiaMethod;
}

//excel导出
function exportExcel(){
	$.ajax({
		type: "POST",
		url: ctx+"/rfqRequestItem/exportRecord",
		data: {
			requestId: $('#requestId').val()
		},
		success: function(data) {
			if ("success"==data.status) {
				/*//预算总价
				var budgetPrice = data.budgetPrice;
				console.log("budgetPrice:"+budgetPrice);*/
				location.href=data.message;
			} else {
				RFQ.error('sorry,出错了！');
			};
		}
	});
}

function saveExcel(){
	//校验是否有输入文件
	var $file = $('#file');
	if(!$file[0].value){
		RFQ.error('您还未选择文件');
		return;
	}
	$('#excelUpload').ajaxSubmit({
		success: function (data) {
            var data;
            try
            {
                data = eval('('+data+')');
            }
            catch (e)
            {
                data = jQuery.parseJSON(jQuery(data).text());          //兼容ie8不返回PRE的解析方式,如果发生异常说明带PRE,部分IE9是带PRE的
            }
			if (data.status == 'success') {
				//预算总价
				var budgetPrice = +data.budgetPrice;
				RFQ.info(data.message);
				$('#cancelPrice33').modal('hide');
				//临时表加载数据
				$('#datatable-requestItemTable').data('_rfqDTable').load();
				//预算价
				totalPrice = budgetPrice;
				$('#totalPrice').html(totalPrice.toFixed(2));
			} else {
				RFQ.error(data.message);
			}
		}
	});
}
